package jgl.vajra.operator.part.vehicle.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import jgl.vajra.operator.R;
import jgl.vajra.operator.bean.OrderDetailsBean;
import jgl.vajra.operator.bean.OrderPaymentDetailsBean;
import jgl.vajra.operator.constant.Constant;
import jgl.vajra.operator.databinding.ActivityOrderDetailsBinding;
import jgl.vajra.operator.dialogFragment.DelayDetailsDialogFragment;
import jgl.vajra.operator.dialogFragment.ModifyContactDialogFragment;
import jgl.vajra.operator.event.OrderDelayEvent;
import jgl.vajra.operator.event.OrderDetailsCancelEvent;
import jgl.vajra.operator.event.PushMachineOrderEvent;
import jgl.vajra.operator.manager.AccountManager;
import jgl.vajra.operator.manager.IntentManager;
import jgl.vajra.operator.manager.SocketPushManager;
import jgl.vajra.operator.netty.MessageBody;
import jgl.vajra.operator.part.home.activity.HomeActivity;
import jgl.vajra.operator.part.vehicle.contract.OrderDetailsContract;
import jgl.vajra.operator.part.vehicle.pop.RestStartPop;
import jgl.vajra.operator.part.vehicle.pop.WaitingTimePop;
import jgl.vajra.operator.part.vehicle.viewModel.OrderDetailsViewModel;
import jgl.vajra.operator.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.operator.widget.mvvm.view.AppActivityManager;
import jgl.vajra.operator.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.operator.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.operator.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.operator.widget.utils.PhoneUtils;
import jgl.vajra.operator.widget.utils.TimeUtils;
import jgl.vajra.operator.widget.utils.ToastUtils;
import jgl.vajra.operator.widget.utils.UIUtils;

@CreateViewModel(OrderDetailsViewModel.class)
public class OrderDetailsActivity extends BaseMVVMActivity<OrderDetailsViewModel, ActivityOrderDetailsBinding> implements OrderDetailsContract.View {

    private String authorization;
    private String orderId;
    private BaiduMap mBaiduMap;
    private MapStatus mapBuild;
    private OrderDetailsBean data;
    private int waitTime = 0;
    private int cumulativeTime = 0;
    private int restTime = 0;
    private int workTime = 0;
    private WaitingTimePop waitingTimePop;
    private double latitude;
    private double longitude;
    private int status = 0;//休息类型状态
    private String remark = "";
    private LocationClient mLocationClient;
    private MyLocationListener myLocationListener;
    private boolean isFirstLocate;
    private RestStartPop restStartPop;
    private OrderPaymentDetailsBean orderPaymentDetailsBean;
    private CountDownTimer timer;
    private int locationNum = 0;//定位次数,失败了次重新获取3次

    private int goingTag = 0;
    private DelayDetailsDialogFragment delayDetailsDialogFragment;

    @Override
    public int getLayoutId() {
        return R.layout.activity_order_details;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);
        authorization = AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization;
        orderId = getIntent().getStringExtra("orderId");

        //滑动按钮
        mBinding.slideView.setUnlockListener(() -> {

            if (data.goingTag == 0) {//开始出发
                Map<String, Object> map = new HashMap<>();
                map.put("Authorization", authorization);
                map.put("orderId", data.orderId);
                mViewModel.getStartData(map);
                return;
            }

            if (data.status > 2) {
                ToastUtils.showShort("请先暂停休息");
                return;
            }
            this.status = 0;
            getWorkingStateData();
        });

        mBinding.tvWaitingFee.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        mBinding.tvWaitingFee.getPaint().setAntiAlias(true);//抗锯齿

        mBinding.mapView.showScaleControl(false);  // 设置比例尺是否可见（true 可见/false不可见）
        mBinding.mapView.showZoomControls(false);  // 设置缩放控件是否可见（true 可见/false不可见）
        View child = mBinding.mapView.getChildAt(1); // 找到百度LOGO控件对象
        if ((child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);  // 设置child这个控件是否可见（VISIBLE 可见/INVISIBLE不可见 /GONE 完全隐藏）
        }

        // 得到地图
        mBaiduMap = mBinding.mapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //定位初始化
        mLocationClient = new LocationClient(this);

        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(60000);//60秒
        // 可选，设置地址信息
        option.setIsNeedAddress(true);
        //可选，设置是否需要地址描述
        option.setIsNeedLocationDescribe(true);

        //设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();

        requestNetData();

        Observable.interval(60, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                if (mLocationClient.isStarted()) {
                    mLocationClient.stop();
                }
                mLocationClient.start();
            }
        });

       /* getLoc();
        //1分钟
        Observable.interval(60, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                getLoc();
            }
        });*/

        //等待时长
        mBinding.tvWaitTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                waitTime++;
                ch.setText(FormatMiss(waitTime));

            }
        });

        //累计时长
        mBinding.tvCumulativeTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                cumulativeTime++;
                ch.setText(FormatMiss(cumulativeTime));

            }
        });

        //休息时长
        mBinding.tvRestTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                restTime++;
                ch.setText(FormatMiss(restTime));

            }
        });

        //干活时长
        mBinding.tvWorkTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                workTime++;
                ch.setText(FormatMiss(workTime));

            }
        });
    }

    private void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", authorization);
        map.put("orderId", orderId);

        mViewModel.getOrderPaymentDetailsData(map);
    }

    private void getWorkingStateData() {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", data.orderId);
        map.put("longitude", longitude);
        map.put("latitude", latitude);
        map.put("status", status);
        map.put("remark", remark);

        mViewModel.getWorkingState(map);
    }

    //延时前往确认
    @Override
    public void onConfirm() {
        if (delayDetailsDialogFragment == null)
            delayDetailsDialogFragment = new DelayDetailsDialogFragment();
        delayDetailsDialogFragment.setDelayDetailsListener(()->{
            requestNetData();
        });
        delayDetailsDialogFragment.setData(orderPaymentDetailsBean);
        delayDetailsDialogFragment.show(getSupportFragmentManager());
    }

    //回到当前位置
    @Override
    public void onReposition() {
        setMapViewAddress(Double.parseDouble(data.latitude), Double.parseDouble(data.longitude));
    }

    //报警
    @Override
    public void onPolice(OrderPaymentDetailsBean data) {
        if(data.payTag==0){
            ToastUtils.showShort("客户还没有付款");
            return;
        }
        PhoneUtils.dial(this, AEACCoder.decrypt(data.contactPhone));
    }

    //发送信息
    @Override
    public void onCustomerService() {
        ToastUtils.showShort("发送信息");
    }

    //分享单子
    @Override
    public void onShareOrder() {
        ToastUtils.showShort("分享订单");
    }

    //取消单子
    @Override
    public void onCancelOrder() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", authorization);
        map.put("orderId", orderId);
        map.put("userType", Constant.USER_TYPE);
        map.put("udid", PhoneUtils.getUDID());

        mViewModel.cancelOrder(map);
    }

    //联系不上
    @Override
    public void onContactNo() {
        ToastUtils.showShort("联系不上");
    }

    //查看更多
    @Override
    public void onChangeDriver() {
        ToastUtils.showShort("查看更多");
    }

    //抢占焦点
    @Override
    public void onText() {

    }

    //等候费
    @Override
    public void onWaitingFee() {
        IntentManager.toWaitingFeeActivity(this);
    }

    //等候时间,开始计时
    @Override
    public void onStartTiming(OrderPaymentDetailsBean data) {

        if (waitingTimePop == null) {
            waitingTimePop = new WaitingTimePop(this, data);
        }
        waitingTimePop.setWaitingTimeListener(() -> {
            mBinding.llTiming.setVisibility(View.VISIBLE);
            mBinding.tvStartTiming.setVisibility(View.GONE);
            mBinding.tvWaitTimer.start();
        });
        waitingTimePop.showPopupWindow(mBinding.getRoot());
    }

    //开始休息或者暂停休息
    @Override
    public void onRest(OrderPaymentDetailsBean data) {
        if (data.status > 2) {
            //暂停休息
            this.status = 9;
            getWorkingStateData();
            return;
        }

        if (restStartPop == null) {
            restStartPop = new RestStartPop(this, data);
        }
        restStartPop.setRestStartListener((status, remark) -> {
            this.status = status;
            this.remark = remark;
            getWorkingStateData();

        });
        restStartPop.showPopupWindow(mBinding.getRoot());
    }

    // 将秒转化成小时分钟
    public String FormatMiss(int miss) {
        String hh = miss / 3600 > 9 ? miss / 3600 + "" : "0" + miss / 3600;
        String mm = (miss % 3600) / 60 > 9 ? (miss % 3600) / 60 + "" : "0" + (miss % 3600) / 60;
//        String ss = (miss % 3600) % 60 > 9 ? (miss % 3600) % 60 + "" : "0" + (miss % 3600) % 60;
        return hh + ":" + mm;
    }


    //返回的数据
    @Override
    public void returnOrderDetailsData(OrderDetailsBean data) {

        if (data.status == 100) {
            finish();
            return;
        }

        restTime = 0;
        this.data = data;

        mBinding.toolbar.setTitleText(data.title);
        orderPaymentDetailsBean.status = data.status;
        orderPaymentDetailsBean.goingTag = data.goingTag;
        orderPaymentDetailsBean.distanceState = data.content;
        orderPaymentDetailsBean.waitState = data.waitState;
        orderPaymentDetailsBean.waitHint = data.waitHint;
        orderPaymentDetailsBean.toAddressState = data.toAddressState;
        orderPaymentDetailsBean.arriveState = data.arriveState;
        orderPaymentDetailsBean.timingTag = data.timingTag;
        orderPaymentDetailsBean.waitingFreeStartTime = data.waitingFreeStartTime;
        orderPaymentDetailsBean.cumulativeDurationHint = data.cumulativeDurationHint;
        orderPaymentDetailsBean.midwayRestHint = data.midwayRestHint;
        orderPaymentDetailsBean.ownerContent = data.ownerContent;
        orderPaymentDetailsBean.content = data.content;
        orderPaymentDetailsBean.buttonStatus = data.buttonStatus;


        mBinding.setData(orderPaymentDetailsBean);

        goingTag = orderPaymentDetailsBean.goingTag;

        mBaiduMap.clear();
        if (!TextUtils.isEmpty(data.latitude)) {
            setMapViewAddress(Double.parseDouble(data.latitude), Double.parseDouble(data.longitude));
            addMaker(Double.parseDouble(data.latitude), Double.parseDouble(data.longitude), data.statusHint);
        }

        if (data.timingTag == 1) {
            waitTime = (int) (System.currentTimeMillis() - TimeUtils.parsStringTimeLong(data.waitingFreeStartTime)) / 1000;
            mBinding.tvWaitTimer.start();
        }

        if (data.status == 1 && data.timingTag == 0) {
            mBinding.tvStartTiming.setVisibility(View.VISIBLE);
        } else {
            mBinding.tvStartTiming.setVisibility(View.GONE);
        }

        //0前往目的地   1到达目的地  2干活中  大于2休息中  100完成订单
        if (data.status == 0 || data.status == 1) {
            mBinding.rlBeforeWork.setVisibility(View.VISIBLE);
        } else {
            mBinding.rlBeforeWork.setVisibility(View.GONE);
            mBinding.tvWaitTimer.stop();
            mBinding.rlAfterWork.setVisibility(View.VISIBLE);

            //累计时长
            cumulativeTime = data.cumulativeDuration * 60;
            mBinding.tvCumulativeTimer.start();

            if (data.status > 2) {
                restTime = (int) (System.currentTimeMillis() - TimeUtils.parsStringTimeLong(data.lastOperateTime)) / 1000;
            }

            //休息时长
            restTime = restTime + data.midwayRest * 60;
            mBinding.tvRestTimer.start();

            //干活时间
            workTime = cumulativeTime - restTime;

            mBinding.tvWorkTimer.start();
            if (data.status == 2) {
                mBinding.tvRestTimer.stop();
            } else if (data.status > 2) {//休息中
                mBinding.tvWorkTimer.stop();
            }
        }
    }

    @Override
    public void returnOrderPaymentDetailsData(OrderPaymentDetailsBean data) {
        data.goingTag = 0;//初始化

        restTime = 0;
        orderPaymentDetailsBean = data;

        if (orderPaymentDetailsBean.payTag !=0) {
            Map<String, Object> map = new HashMap<>();
            map.put("Authorization", authorization);
            map.put("orderId", orderId);
            mViewModel.getOrderDetailsData(map);
        } else {
            mBinding.tvStartTiming.setVisibility(View.GONE);
            mBinding.toolbar.setTitleText(orderPaymentDetailsBean.ownerTitle);
            mBinding.setData(orderPaymentDetailsBean);
            getCountDownTimer();

            if (data.jobAddressList != null && data.jobAddressList.size() != 0)
                if (!TextUtils.isEmpty(data.jobAddressList.get(0).latitude)) {
                    setMapViewAddress(Double.parseDouble(data.jobAddressList.get(0).latitude), Double.parseDouble(data.jobAddressList.get(0).longitude));
                    addMaker(Double.parseDouble(data.jobAddressList.get(0).latitude), Double.parseDouble(data.jobAddressList.get(0).longitude), data.jobAddressList.get(0).address);
                }
        }

    }

    @Override
    public void returnCancelOrder() {
        ToastUtils.showShort("取消成功");
        AppActivityManager.getAppActivityManager().returnToActivity(HomeActivity.class);
    }

    @Override
    public void returnStartData() {
        if (mLocationClient.isStarted()) {
            mLocationClient.stop();
        }
        mLocationClient.start();
        requestNetData();
    }

    public void getCountDownTimer() {
        long countDown = (System.currentTimeMillis() - TimeUtils.parsDataTimeLong(orderPaymentDetailsBean.pickUpTime));
        if (countDown >= 600000) {
            mBinding.llHead.setVisibility(View.GONE);
            timerCancel();
        } else {
            mBinding.llHead.setVisibility(View.VISIBLE);

            long newCountDown = 600000 - countDown;
            /**
             * 倒数计时器
             */
            timer = new CountDownTimer(newCountDown, 1000) {
                /**
                 * 固定间隔被调用,就是每隔countDownInterval会回调一次方法onTick
                 * @param millisUntilFinished
                 */
                @Override
                public void onTick(long millisUntilFinished) {
                    mBinding.tvTime.setText(formatTime(millisUntilFinished));
                }

                /**
                 * 倒计时完成时被调用
                 */
                @Override
                public void onFinish() {
                    mBinding.tvTime.setText("00:00");
                }
            };
            timerStart();
        }
    }

    /**
     * 将毫秒转化为 分钟：秒 的格式
     *
     * @param millisecond 毫秒
     * @return
     */
    public String formatTime(long millisecond) {
        int minute;//分钟
        int second;//秒数
        minute = (int) ((millisecond / 1000) / 60);
        second = (int) ((millisecond / 1000) % 60);
        if (minute < 10) {
            if (second < 10) {
                return "0" + minute + ":" + "0" + second;
            } else {
                return "0" + minute + ":" + second;
            }
        } else {
            if (second < 10) {
                return minute + ":" + "0" + second;
            } else {
                return minute + ":" + second;
            }
        }
    }

    /**
     * 取消倒计时
     */
    public void timerCancel() {
        if (timer != null)
            timer.cancel();
    }

    /**
     * 开始倒计时
     */
    public void timerStart() {
        if (timer != null)
            timer.start();
    }

    public void setMapViewAddress(double latitude, double longitude) {
        LatLng ll = new LatLng(latitude, longitude);
        mapBuild = new MapStatus.Builder()
                .target(ll)
                .zoom(18f)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapBuild);
        //改变地图状态
        mBaiduMap.animateMapStatus(mMapStatusUpdate);
    }

    public void addMaker(double longitude, double latitude, String statusHint) {

        //定义Maker坐标点
        LatLng point = new LatLng(longitude, latitude);
        View view = View.inflate(OrderDetailsActivity.this, R.layout.view_marker_order_details, null);
        TextView tvStatusHint = view.findViewById(R.id.tv_status_hint);
        tvStatusHint.setText(statusHint);
        //构建Marker图标
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions options = new MarkerOptions()
                .position(point)
                .icon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view)));
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(options);

    }

    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();

        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }

    public void getLoc() {
        // 位置
        final String contextService = Context.LOCATION_SERVICE;
        String provider;
        LocationManager locationManager = (LocationManager) getSystemService(contextService);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);// 高精度
        criteria.setAltitudeRequired(false);// 不要求海拔
        criteria.setBearingRequired(false);// 不要求方位
        criteria.setCostAllowed(true);// 允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);// 低功耗
        // 从可用的位置提供器中，匹配以上标准的最佳提供器
        provider = locationManager.getBestProvider(criteria, false);
        // 获得最后一次变化的位置
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();

        }
        LocationListener locationListener = new LocationListener() {
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
                // TODO Auto-generated method stub
            }

            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub
            }

            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub
            }

            public void onLocationChanged(Location location) {


            }
        };
        // 监听位置变化，60秒一次，距离10米以上
        locationManager.requestLocationUpdates(provider, 30000, 10,
                locationListener);
    }

    // 继承抽象类BDAbstractListener并重写其onReceieveLocation方法来获取定位数据，并将其传给MapView
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mBinding.mapView == null) {
                return;
            }

            // 如果是第一次定位
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            if (isFirstLocate) {
                isFirstLocate = false;
                //给地图设置状态
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(ll));
            }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            // ------------------  以下是可选部分 ------------------
          /*  // 自定义地图样式，可选
            // 更换定位图标，这里的图片是放在 drawble 文件下的
            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
            // 定位模式 地图SDK支持三种定位模式：NORMAL（普通态）, FOLLOWING（跟随态）, COMPASS（罗盘态）
            locationMode = MyLocationConfiguration.LocationMode.NORMAL;
            // 定位模式、是否开启方向、设置自定义定位图标、精度圈填充颜色以及精度圈边框颜色5个属性（此处只设置了前三个）。
            MyLocationConfiguration mLocationConfiguration = new MyLocationConfiguration(locationMode,true,mCurrentMarker);
            // 使自定义的配置生效
            mBaiduMap.setMyLocationConfiguration(mLocationConfiguration);*/

            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, BitmapDescriptorFactory.fromResource(R.drawable.ic_current_location)));

            // ------------------  可选部分结束 ------------------

            // 显示当前信息
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("\n经度：" + location.getLatitude());
            stringBuilder.append("\n纬度：" + location.getLongitude());
            stringBuilder.append("\n状态码：" + location.getLocType());
            stringBuilder.append("\n国家：" + location.getCountry());
            stringBuilder.append("\n城市：" + location.getCity());
            stringBuilder.append("\n区：" + location.getDistrict());
            stringBuilder.append("\n街道：" + location.getStreet());
            stringBuilder.append("\n地址：" + location.getAddrStr());

            latitude = location.getLatitude();
            longitude = location.getLongitude();

            Logger.d(goingTag + "推送经纬度当前信息" + stringBuilder.toString());
            //经度范围:73-136 纬度范围3-54
            //失败了立马重新获取,三次都失败就等下一次

            //Logger.d("推送经纬度当前信息" +goingTag+"=="+data.status+"=="+latitude);
            if (goingTag == 1 && data.status == 0) {//开始出发-到达目的地才推送
                if (4.9E-324 != latitude) {
                    locationNum = 0;
                    //推送经纬度
                    SocketPushManager.getInstance().pushLatitudeLongitude(longitude + "&&" + latitude + "&&" + orderId);
                } else {
                    if (locationNum < 3) {
                        locationNum = locationNum + 1;
                        if (mLocationClient.isStarted()) {
                            mLocationClient.stop();
                        }
                        mLocationClient.start();
                    }
                }
            }

            if (mLocationClient.isStarted()) {
                mLocationClient.stop();
            }
        }
    }

    @Override
    protected void onStart() {
        mLocationClient.start();
        super.onStart();
    }

    @Override
    protected void onResume() {
        mBinding.mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mBinding.mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocationClient.unRegisterLocationListener(myLocationListener);
        mLocationClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mBaiduMap.clear();
        mBinding.mapView.onDestroy();
        mBaiduMap = null;
        super.onDestroy();
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushMachineOrderEvent(PushMachineOrderEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        if (String.valueOf(messageInfo.orderId).equals(orderId)) {
            requestNetData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderDetailsCancelEvent(OrderDetailsCancelEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        if (String.valueOf(messageInfo.orderId).equals(orderId)) {
            ToastUtils.showShort("客户取消订单了");
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderDelayEvent(OrderDelayEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        if (String.valueOf(messageInfo.orderId).equals(orderId)) {
            requestNetData();
        }
    }
}
